# -*- coding: utf-8 -*-
"""
MetasoCreator 快速体验脚本
功能：启动简化版后端服务，无需数据库依赖
作者：东篱馆主
创建时间：2025-01-19
修改时间：2025-01-19
"""

import os
import sys
import webbrowser
import time
import threading
from pathlib import Path

def create_simple_app():
    """创建简化版Flask应用"""
    try:
        from flask import Flask, jsonify, request, send_from_directory
        from flask_cors import CORS
        
        app = Flask(__name__)
        CORS(app)
        
        # 模拟数据存储
        content_store = {}
        search_history = {}
        
        @app.route('/')
        def index():
            return '''
            <!DOCTYPE html>
            <html>
            <head>
                <title>MetasoCreator 快速体验</title>
                <meta charset="utf-8">
                <style>
                    body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
                    .demo-section { margin: 30px 0; padding: 20px; border: 1px solid #ddd; border-radius: 8px; }
                    .btn { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; margin: 5px; }
                    .btn:hover { background: #0056b3; }
                    .response { background: #f8f9fa; padding: 15px; border-radius: 4px; margin-top: 10px; font-family: monospace; }
                    input, textarea, select { width: 100%; padding: 8px; margin: 5px 0; border: 1px solid #ddd; border-radius: 4px; }
                    .form-group { margin: 15px 0; }
                </style>
            </head>
            <body>
                <h1>🚀 MetasoCreator 快速体验</h1>
                <p>这是一个简化版演示，展示了系统的核心功能。无需数据库，所有数据存储在内存中。</p>
                
                <div class="demo-section">
                    <h2>🔍 智能搜索模拟</h2>
                    <div class="form-group">
                        <label>搜索关键词:</label>
                        <input type="text" id="searchQuery" value="人工智能" placeholder="输入搜索关键词">
                    </div>
                    <div class="form-group">
                        <label>搜索范围:</label>
                        <select id="searchScope">
                            <option value="web">全网搜索</option>
                            <option value="academic">学术搜索</option>
                        </select>
                    </div>
                    <button class="btn" onclick="simulateSearch()">🔍 开始搜索</button>
                    <div id="searchResponse" class="response" style="display:none;"></div>
                </div>
                
                <div class="demo-section">
                    <h2>📝 内容管理</h2>
                    <div class="form-group">
                        <label>标题:</label>
                        <input type="text" id="contentTitle" value="我的第一篇文章" placeholder="输入标题">
                    </div>
                    <div class="form-group">
                        <label>内容:</label>
                        <textarea id="contentBody" rows="4" placeholder="输入内容...">这是一篇关于人工智能的文章。AI技术正在改变我们的世界...</textarea>
                    </div>
                    <div class="form-group">
                        <label>类型:</label>
                        <select id="contentType">
                            <option value="article">文章</option>
                            <option value="note">笔记</option>
                            <option value="summary">摘要</option>
                        </select>
                    </div>
                    <button class="btn" onclick="createContent()">✨ 创建内容</button>
                    <button class="btn" onclick="listContent()">📋 查看列表</button>
                    <div id="contentResponse" class="response" style="display:none;"></div>
                </div>
                
                <div class="demo-section">
                    <h2>⚙️ 系统状态</h2>
                    <button class="btn" onclick="checkHealth()">💚 健康检查</button>
                    <div id="healthResponse" class="response" style="display:none;"></div>
                </div>
                
                <script>
                    function showResponse(elementId, data, isSuccess = true) {
                        const element = document.getElementById(elementId);
                        element.style.display = 'block';
                        element.innerHTML = JSON.stringify(data, null, 2);
                        element.style.backgroundColor = isSuccess ? '#d4edda' : '#f8d7da';
                    }
                    
                    async function simulateSearch() {
                        const query = document.getElementById('searchQuery').value;
                        const scope = document.getElementById('searchScope').value;
                        
                        const mockResults = {
                            success: true,
                            query: query,
                            search_scope: scope,
                            results: [
                                {
                                    title: `${query} - 最新发展动态`,
                                    url: 'https://example.com/ai-news',
                                    snippet: `关于${query}的最新研究进展和应用案例...`,
                                    source: '科技新闻网',
                                    relevance_score: 0.95
                                },
                                {
                                    title: `${query}技术详解`,
                                    url: 'https://example.com/ai-tech',
                                    snippet: `深入解析${query}的核心技术和实现原理...`,
                                    source: '技术博客',
                                    relevance_score: 0.88
                                },
                                {
                                    title: `${query}应用前景`,
                                    url: 'https://example.com/ai-future',
                                    snippet: `${query}在各个领域的应用前景和发展趋势...`,
                                    source: '行业分析',
                                    relevance_score: 0.82
                                }
                            ],
                            total_results: 3,
                            suggestions: [`${query}教程`, `${query}最新消息`, `${query}应用案例`],
                            message: '搜索完成（模拟数据）'
                        };
                        
                        showResponse('searchResponse', mockResults, true);
                    }
                    
                    async function createContent() {
                        const title = document.getElementById('contentTitle').value;
                        const content = document.getElementById('contentBody').value;
                        const type = document.getElementById('contentType').value;
                        
                        if (!title || !content) {
                            alert('请填写标题和内容');
                            return;
                        }
                        
                        const mockResponse = {
                            success: true,
                            message: '内容创建成功（模拟）',
                            data: {
                                id: 'demo_' + Date.now(),
                                title: title,
                                type: type,
                                created_at: new Date().toISOString(),
                                word_count: content.length
                            }
                        };
                        
                        showResponse('contentResponse', mockResponse, true);
                    }
                    
                    async function listContent() {
                        const mockResponse = {
                            success: true,
                            data: {
                                contents: [
                                    {
                                        id: 'demo_1',
                                        title: '人工智能入门指南',
                                        type: 'article',
                                        created_at: '2025-01-19T10:00:00',
                                        word_count: 1500
                                    },
                                    {
                                        id: 'demo_2',
                                        title: '机器学习笔记',
                                        type: 'note',
                                        created_at: '2025-01-19T09:30:00',
                                        word_count: 800
                                    }
                                ],
                                total: 2,
                                page: 1,
                                limit: 10
                            }
                        };
                        
                        showResponse('contentResponse', mockResponse, true);
                    }
                    
                    async function checkHealth() {
                        const mockResponse = {
                            status: 'healthy',
                            service: 'MetasoCreator Demo',
                            version: '1.0.0',
                            timestamp: new Date().toISOString(),
                            message: '系统运行正常（模拟状态）'
                        };
                        
                        showResponse('healthResponse', mockResponse, true);
                    }
                </script>
            </body>
            </html>
            '''
        
        @app.route('/api/health')
        def health_check():
            return jsonify({
                'status': 'healthy',
                'service': 'MetasoCreator Demo',
                'version': '1.0.0',
                'timestamp': time.strftime('%Y-%m-%dT%H:%M:%S'),
                'message': 'API服务运行正常'
            })
        
        @app.route('/api/search/', methods=['POST'])
        def search_api():
            data = request.get_json()
            query = data.get('q', '')
            
            # 模拟搜索结果
            results = [
                {
                    'title': f'{query} - 搜索结果1',
                    'url': f'https://example.com/search1?q={query}',
                    'snippet': f'这是关于"{query}"的搜索结果...',
                    'source': '示例网站',
                    'relevance_score': 0.95
                },
                {
                    'title': f'{query} - 搜索结果2',
                    'url': f'https://example.com/search2?q={query}',
                    'snippet': f'另一个关于"{query}"的搜索结果...',
                    'source': '示例网站',
                    'relevance_score': 0.88
                }
            ]
            
            return jsonify({
                'success': True,
                'query': query,
                'results': results,
                'total_results': len(results),
                'message': '搜索完成（模拟数据）'
            })
        
        @app.route('/api/content/', methods=['POST'])
        def create_content_api():
            data = request.get_json()
            
            content_id = f'demo_{int(time.time())}'
            content_store[content_id] = {
                'id': content_id,
                'title': data.get('title', ''),
                'content': data.get('content', ''),
                'type': data.get('type', 'article'),
                'tags': data.get('tags', []),
                'created_at': time.strftime('%Y-%m-%dT%H:%M:%S'),
                'updated_at': time.strftime('%Y-%m-%dT%H:%M:%S')
            }
            
            return jsonify({
                'success': True,
                'message': '内容创建成功',
                'data': content_store[content_id]
            }), 201
        
        @app.route('/api/content/list')
        def list_content_api():
            contents = list(content_store.values())
            return jsonify({
                'success': True,
                'data': {
                    'contents': contents,
                    'total': len(contents),
                    'page': 1,
                    'limit': 10
                }
            })
        
        return app
        
    except ImportError as e:
        print(f"❌ 缺少必要的依赖包: {e}")
        print("请运行: pip install flask flask-cors -i https://pypi.tuna.tsinghua.edu.cn/simple")
        return None

def main():
    """主函数"""
    print("=" * 60)
    print("🚀 MetasoCreator 快速体验启动器")
    print("=" * 60)
    
    # 创建简化版应用
    app = create_simple_app()
    if not app:
        sys.exit(1)
    
    print("✅ 简化版应用创建成功")
    print("📋 功能说明:")
    print("1. 🔍 智能搜索模拟 - 体验搜索功能")
    print("2. 📝 内容管理 - 创建和查看内容")
    print("3. ⚙️ 系统状态 - 健康检查")
    print("\n💡 这是一个演示版本，所有数据存储在内存中")
    
    print("\n" + "=" * 60)
    
    # 在新线程中打开浏览器
    def open_browser():
        time.sleep(2)
        url = "http://127.0.0.1:5000"
        print(f"🌐 打开演示页面: {url}")
        try:
            webbrowser.open(url)
            print("✅ 演示页面已在新浏览器窗口中打开")
        except:
            print(f"请手动在浏览器中访问: {url}")
    
    browser_thread = threading.Thread(target=open_browser)
    browser_thread.daemon = True
    browser_thread.start()
    
    # 启动应用
    print("🚀 启动演示服务...")
    app.run(host='127.0.0.1', port=5000, debug=False)

if __name__ == '__main__':
    main() 